import hashlib
import json
import time
import jwt
from django.conf import settings
from django.http import JsonResponse
from user.models import UserProfile
from carts.views import CartsView
# Create your views here.
def tokens(request):
    '''
    登录功能视图逻辑10200-10299
    1.获取请求体的数据【用户名，密码】
    2.判断用户名是否存在
    3.判断密码是否正确
    4.组织数据返回
    '''
    data = json.loads(request.body)
    username = data.get("username")
    password = data.get("password")
    try:
        user = UserProfile.objects.get(username=username)
    except Exception as e:
        print("e------------------->", e)
        return JsonResponse({"code":10200, "error":f"The {username} isn't exist!!"})
    # 判断密码
    m = hashlib.md5()
    m.update(password.encode())
    pwd_md5 = m.hexdigest()
    if pwd_md5 != user.password:
        return JsonResponse({"code":102001, "error":f"The {username}'password is wrong!!"})
    # 签发token
    token = make_token(username)
    
    # 购物车数据合并
    offline_data = data.get("carts")
    carts_count = CartsView().merge_carts(offline_data, user.id)

    # 返回数据
    result = {
        "code": "200",
        "username":username,
        "data":{"token":token},
        "carts_count":carts_count
    }
    return JsonResponse(result)

def make_token(uname, expire=3600*24):
    '''
    生成token
    :param uname:用户名
    ：return :token
    '''
    payload = {
        "exp" : int(time.time()) + expire,
        "username":uname
    }
    key = settings.JWT_TOKEN_KEY
    return jwt.encode(payload, key, algorithm="HS256")